<template>
  <div>
    <el-dialog
      :title="!dataForm.id ? '新增' : '修改'"
      :close-on-click-modal="false"
      :visible.sync="visible">
      <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="150px" size="small">
        <el-form-item label="区域名称" prop="parentBuildingName" >
          <!--<el-popover-->
            <!--ref="menuListPopover"-->
            <!--placement="bottom-start"-->
            <!--trigger="click">-->
            <!--<div style="height: 350px">-->
              <!--<el-scrollbar style="height: 100%;width: 100%">-->
                <!--<el-tree-->
                  <!--:data="menuList"-->
                  <!--:props="menuListTreeProps"-->
                  <!--node-key="buildingId"-->
                  <!--ref="menuListTree"-->
                  <!--@current-change="menuListTreeCurrentChangeHandle"-->
                  <!--:default-expand-all="true"-->
                  <!--:highlight-current="true"-->
                  <!--:expand-on-click-node="false">-->
                <!--</el-tree>-->
              <!--</el-scrollbar>-->
            <!--</div>-->
          <!--</el-popover>-->
          <el-input v-model="dataForm.buildingName" v-popover:menuListPopover disabled :readonly="true" placeholder="点击选择所属区域" class="menu-list__input"></el-input>
        </el-form-item>

        <el-form-item label="表具类型" prop="deviceType">
          <el-radio v-model="dataForm.deviceType" label="0">实体表</el-radio>
          <el-radio v-model="dataForm.deviceType" label="1">虚拟热水表</el-radio>
        </el-form-item>

      <el-form-item label="计量器编码" prop="meterCode" v-if="dataForm.deviceType === '0'">
          <el-input placeholder="请选择计量器编码"
            style="width:100%"
            class="filter-item"
            @click.native="inputMeterCodeName()"
            v-model="dataForm.meterCodeName">
          </el-input>
        <!-- <el-select v-model="dataForm.meterCode" filterable  @change="changeMeter" style="width:100%">
          <el-option v-for="item in meterInfoList" :key="item.meterCode" :label="item.meterCode+'['+item.meterAddr+']'" :value="item.meterCode"/>
        </el-select> -->
      </el-form-item>

        <el-form-item label="计量器编码" prop="meterCode"  v-if="dataForm.deviceType === '1'">
          <el-select v-model="dataForm.meterCode"  placeholder="请选择"  filterable @change="changeMeterForHot" style="width:100%">
            <el-option
              v-for="(item, index) in hotmeterInfoList" :key="index"
              :label="item.vmeterName +'['+item.vmeterCode+']'"
              :value="item.vmeterCode">
            </el-option>
          </el-select>
        </el-form-item>
      <el-form-item label="计量器名称" prop="deviceName">
        <el-input v-model="dataForm.deviceName" placeholder="计量器名称"> </el-input>
      </el-form-item>
      <el-form-item label="表类型" prop="subitemType">
        <el-select v-model="dataForm.subitemType" style="width:100%" @change="dataForm.subitemValue='0'">
          <el-option v-for="item in subitemTypeList" :key="item.paramValue" :label="item.paramValue" :value="item.paramKey" />
        </el-select>
      </el-form-item>
      <el-form-item label="采集分项" prop="subitemValue" v-show="dataForm.subitemType == '1'">
        <el-select v-model="dataForm.subitemValue" style="width:100%">
          <el-option v-for="item in subitemValueList" :key="item.paramValue" :label="item.paramValue" :value="item.paramKey" />
        </el-select>
      </el-form-item>
        <el-form-item label="是否总表" prop="isTop">
          <el-radio v-model="dataForm.isTop" label="1" @change="changeIstop">是</el-radio>
          <el-radio v-model="dataForm.isTop" label="2"  @change="changeIstop">否</el-radio>
        </el-form-item>
        <el-form-item label="入口线路计量器编码" prop="parentMeterCodeName" v-if="dataForm.isTop=='2'">
        <el-input placeholder="请选择入口线路计量器编码"
            style="width:100%"
            class="filter-item"
            @click.native="inputParentMeterCodeName()"
            v-model="dataForm.parentMeterCodeName">
          </el-input>
      </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false" size="small">取消</el-button>
        <el-button type="primary" @click="dataFormSubmit()" size="small">确定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="入口线路计量器编码" :visible.sync="showTree">
        <el-tree
          :style="'height:'+containerHeight+'px'"
          ref="buildTree"
          highlight-current
          node-key="id"
          :data="treeDataList"
          :expand-on-click-node="false"
          :props="menuListTreeProps"
          @node-click="selectBuild"
          default-expand-all
        >
        <span class="custom-tree-node"  slot-scope="{ node, data }">
          <span :dataType="data.type">
              <!-- <i class="el-icon-setting"  v-if="data.type=='b'"></i> -->
              <i class="el-icon-star-off"  v-if="data.type=='d'"></i>
              {{ node.label }}
          </span>
        </span>
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showTree = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="请选择计量器" :visible.sync="showMeterTree">
        <el-tree
          :style="'height:'+(containerHeight-150)+'px'"
          ref="buildTree"
          highlight-current
          node-key="id"
          :data="treeMeterDataList"
          :expand-on-click-node="false"
          :props="menuListTreeProps"
          @node-click="selectMeterBuild"
          default-expand-all
        >
        <span class="custom-tree-node"  slot-scope="{ node, data }">
          <span :dataType="data.type">
              <!-- <i class="el-icon-setting"  v-if="data.type=='b'"></i> -->
              <i class="el-icon-star-off"  v-if="data.type=='d'"></i>
              {{ node.label }}
          </span>
        </span>
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showMeterTree = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { treeDataTranslate } from '@/utils'
  import * as Util from "@/utils";
  export default {
    data () {
      return {
        showMeterTree:false,
        treeMeterDataList:[],
        showTree:false,
        menuListTreeProps: {
          label: "name",
          children: "children"
        },
        treeDataList:[],
        visible: false,
        materMap : new Map(),
        dataForm: {
          id: 0,
          buildingId: '',
          buildingName:'',
          meterCode: '',
          meterCodeName:'',
          meterType: '',
          subitemType: '',
          subitemValue: '0',
          parentMeterCode: '-1',
          parentMeterCodeName:'',
          deviceName:'',
          isTop:'1',
          deviceType:'0'
        },
        subitemTypeList:[],
        subitemValueList:[],
        meterInfoList:[],
        hotmeterInfoList:[],
        menuList: [],
        dataRule: {
          buildingId: [
            { required: true, message: '区域不能为空', trigger: 'blur' }
          ],
          meterCode: [
            { required: true, message: '计量器编码不能为空', trigger: 'change' }
          ],
          deviceName:[
            { required: true, message: '计量器名称不能为空', trigger: 'blur' }
          ],
          meterType: [
            { required: true, message: '计量器类型不能为空', trigger: 'blur' }
          ],
          subitemType: [
            { required: true, message: '表类型不能为空', trigger: 'blur' }
          ],
          subitemValue: [
            { required: true, message: '采集分类不能为空', trigger: 'blur' }
          ],
          parentMeterCodeName: [
            { required: true, message: '入口线路计量器不能为空', trigger: 'change' }
          ],
          deviceType: [
            { required: true, message: '不能为空', trigger: 'change' }
          ]

        }
      }
    },
    computed: {
      containerHeight() {
        return Util.getClientHeight() - 243;
      },
    },
    created(){
      this.getBuildDeviceList();

    },
    methods: {
      // 获取热水表数据列表
      getHotDataList () {
        this.$api.okhttp({
          url: this.$http.adornUrl('/ecs/ecshotmeterinfo/list'),
          method: 'get',
          params: this.$http.adornParams({
            'page': 1,
            'limit': 10000000,
            "customerId": this.$util.cookies.get('customer_id'),
            'projectid': this.$util.cookies.get("cuuren_projectId")
          })
        }).then((data) => {
          if (data && data.code === 0) {
          this.hotmeterInfoList = data.page.list
          for(var item of this.hotmeterInfoList){
            this.materMap.set(item.vmeterCode,'9');
          }
        } else {
          this.hotmeterInfoList = []
        }
      })
      },
      changeIstop(){
        if(this.dataForm.isTop==='1'){
          this.dataForm.parentMeterCode='-1'
        }
      },
      init (id,subitemTypeList,subitemValueList,meterInfoList,currentbuildInfo) {
        this.getHotDataList();
        this.getMeterTreeList();
        this.meterInfoList = meterInfoList
        this.subitemTypeList = subitemTypeList
        this.subitemValueList =subitemValueList
        this.dataForm.id = id || 0
        this.dataForm.buildingId = id || 0

        for(var item of meterInfoList){
          this.materMap.set(item.meterCode,item.meterType);
        }

        this.$api.okhttp({
          url: this.$http.adornUrl('/ecs/ecsbuildinginfo/select'),
          method: 'get',
          params: this.$http.adornParams({
            'showFlag':"0",
            'buildingid': this.dataForm.buildingId,
            'projectid': this.$util.cookies.get("cuuren_projectId"),
            "customerId": this.$util.cookies.get('customer_id'),
          })
        }).then((data) => {
          this.menuList = treeDataTranslate(data.menuList, 'buildingId','parentBuildingId')
        }).then(() => {
          this.visible = true
          this.$nextTick(() => {
            this.$refs['dataForm'].resetFields()
             this.dataForm.meterCodeName =''
             this.dataForm.parentMeterCodeName =''
          })
        }).then(() => {
          if (this.dataForm.id) {
            this.$api.okhttp({
              url: this.$http.adornUrl(`/ecs/ecsbuildingmeter/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then((data) => {
              if (data && data.code === 0) {
                this.dataForm.buildingId = data.ecsbuildingmeter.buildingId
                this.dataForm.deviceName = data.ecsbuildingmeter.deviceName
                this.dataForm.meterCode = data.ecsbuildingmeter.meterCode
                this.dataForm.meterType = data.ecsbuildingmeter.meterType
                this.dataForm.subitemType = data.ecsbuildingmeter.subitemType
                this.dataForm.subitemValue = data.ecsbuildingmeter.subitemValue
                this.dataForm.parentMeterCode = data.ecsbuildingmeter.parentMeterCode
                this.dataForm.meterCodeName =data.ecsbuildingmeter.meterCode
                this.dataForm.parentMeterCodeName =data.ecsbuildingmeter.parentMeterCode
                this.dataForm.buildingName = currentbuildInfo.buildingName
                if(data.ecsbuildingmeter.parentMeterCode==='-1'){
                  this.dataForm.isTop = '1'
                }else{
                  this.dataForm.isTop = '2'
                }
              //  this.menuListTreeSetCurrentNode()
                this.queryStatic('SUBITEM_VAL',data.ecsbuildingmeter.meterType);

                //热水
                if(data.ecsbuildingmeter.meterType ==this.$meterType.HOT_WATER){
                  this.dataForm.deviceType = '1'
                }

              }else{
            // 新增
             //  this.menuListTreeSetCurrentNode()
               this.dataForm.buildingName =''
             }
            })
          }else{
          this.dataForm.buildingId = currentbuildInfo.buildingId
          this.dataForm.buildingName = currentbuildInfo.buildingName
        }
        })
      },
      getMeterTreeList(){
        this.$api.okhttp({
          url: this.$http.adornUrl("/ecs/ecsmeterinfo/getDeviceTree"),
          method: "get",
          params: this.$http.adornParams({
            "buildingId":this.dataForm.buildingId,
            "customerId": this.$util.cookies.get('customer_id'),
            'projectId': this.$util.cookies.get("cuuren_projectId"),
          })
        }).then(res=>{
           if (res && res.code == 0) {
            this.treeMeterDataList = Util.treeDataTranslate(res.data,"id","pid");
          }
        })
      },
      getBuildDeviceList(){
        this.$api.okhttp({
          url: this.$http.adornUrl("/ecs/ecsbuildinginfo/getDeviceTree"),
          method: "get",
          params: this.$http.adornParams({
            'projectId': this.$util.cookies.get("cuuren_projectId"),
            "customerId": this.$util.cookies.get('customer_id'),
            "meterType": this.dataForm.meterType
          })
        }).then(res=>{
          if (res && res.code == 0) {
            if(res.data&&res.data.length>0){
              res.data.forEach(ele=>{
                ele.name = `${ele.id}[${ele.name}]`;
              })
            }
            this.treeDataList = Util.treeDataTranslate(res.data,"id","pid");
          }
        })
      },
      inputParentMeterCodeName(){
        this.showTree = true;
      },
      inputMeterCodeName(){
        this.showMeterTree = true;
      },
      changeMeterForHot(){
        this.dataForm.deviceName = this.hotmeterInfoList.find(item=>item.vmeterCode==this.dataForm.meterCode).vmeterName
        this.changeMeter( this.dataForm.meterCode)
      },
      selectBuild(data){
        if(data.type=='d'){
          this.dataForm.parentMeterCode = data.id;
          this.dataForm.parentMeterCodeName = data.name;
          this.showTree = false;
        }
      },
      selectMeterBuild(data){
        if(data.type=='m'){
          this.dataForm.meterCode = data.id;
          this.dataForm.meterCodeName = data.name;
          this.dataForm.deviceName = data.simpleName;
          this.dataForm.meterType = data.meterType;
          this.showMeterTree = false;
          this.changeMeter(data.id)
          this.getBuildDeviceList()
        }
      },
      changeMeter(value){
        this.dataForm.subitemValue = '0'
        this.queryStatic('SUBITEM_VAL',this.materMap.get(value))
      },
      /**
       * 获取参数枚举
       */
      queryStatic(type,paramValue) {
        this.$api.okhttp({
          url: this.$http.adornUrl("/sys/sysstaticdata/getList"),
          method: "get",
          params: this.$http.adornParams({
            code: type,
            paramValue:paramValue,
            customerId: this.$util.cookies.get("customer_id")
          })
        }).then((data) => {
          if (data && data.code === 0) {
            this.subitemValueList = data.page;
        }
      });
      },
      // 菜单树选中
      menuListTreeCurrentChangeHandle (data, node) {
        this.dataForm.buildingId = data.buildingId
        this.dataForm.buildingName = data.buildingName
      },
      // 菜单树设置当前选中节点
      menuListTreeSetCurrentNode () {
        this.$refs.menuListTree.setCurrentKey(this.dataForm.buildingId)
        this.dataForm.buildingName = (this.$refs.menuListTree.getCurrentNode() || {})['buildingName']
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$api.okhttp({
              url: this.$http.adornUrl(`/ecs/ecsbuildingmeter/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'buildingId': this.dataForm.buildingId,
                'meterCode': this.dataForm.meterCode,
                'deviceName': this.dataForm.deviceName,
                'meterType': this.dataForm.meterType,
                'subitemType': this.dataForm.subitemType,
                'subitemValue': this.dataForm.subitemValue,
                'parentMeterCode': this.dataForm.parentMeterCode,
                "customerId": this.$util.cookies.get('customer_id'),
              })
            }).then((data) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      }
    },
    watch:{
      'dataForm.subitemType'(newValue,oldValue){
        if(this.dataForm.subitemType==0){
          this.getBuildDeviceList();
        }
      }
    }
  }
</script>
<style scoped lang="scss">

  @import "../../assets/scss/_variables";
  .objectTree {
      position: absolute;
      overflow: auto;
      z-index: 100;
      height: 200px;
      /* border: 1px solid #ddd; */
      line-height: normal;
      z-index: 204;
      box-shadow: 0px 0px 1px 1px #e2dfdf;
      margin-top: 3px;
      border-radius: 4px;
    background-color: white;
  }
</style>
